/**
 * 信访台账详情页面JavaScript
 */

// 简单的通知服务
const NotificationService = {
    success: function(message) {
        console.log('成功:', message);
    },
    error: function(message) {
        console.error('错误:', message);
        alert('错误: ' + message);
    },
    warning: function(message) {
        console.warn('警告:', message);
        alert('警告: ' + message);
    },
    info: function(message) {
        console.info('信息:', message);
    }
};

// 显示/隐藏加载提示
function showLoading() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.classList.remove('hidden');
    }
}

function hideLoading() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.classList.add('hidden');
    }
}

class PetitionLedgerDetail {
    constructor(recordId) {
        this.recordId = recordId;
        this.data = null;
        this.init();
    }

    async init() {
        try {
            await this.loadDetail();
            this.bindEvents();
        } catch (error) {
            console.error('初始化详情页面失败:', error);
            NotificationService.error('加载详情失败');
        }
    }

    bindEvents() {
        // 绑定返回按钮
        const backBtn = document.getElementById('backBtn');
        if (backBtn) {
            backBtn.addEventListener('click', () => {
                window.location.href = '/web/petition-ledger';
            });
        }

        // 绑定导出按钮
        const exportBtn = document.getElementById('exportDetailBtn');
        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                this.exportDetail();
            });
        }

        // 绑定标签页切换
        this.initTabSwitching();
    }

    initTabSwitching() {
        // 绑定标签页按钮点击事件
        const tabButtons = document.querySelectorAll('.tab-button');
        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                const tabName = button.getAttribute('data-tab');
                this.switchTab(tabName);
            });
        });
    }

    switchTab(tabName) {
        // 隐藏所有标签页内容
        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach(content => {
            content.classList.add('hidden');
        });

        // 移除所有标签页按钮的激活状态
        const tabButtons = document.querySelectorAll('.tab-button');
        tabButtons.forEach(button => {
            button.classList.remove('active', 'border-indigo-500', 'text-indigo-600');
            button.classList.add('border-transparent', 'text-slate-500');
        });

        // 显示选中的标签页内容
        const selectedTab = document.getElementById(`${tabName}-tab`);
        if (selectedTab) {
            selectedTab.classList.remove('hidden');
        }

        // 激活选中的标签页按钮
        const activeButton = document.querySelector(`[data-tab="${tabName}"]`);
        if (activeButton) {
            activeButton.classList.add('active', 'border-indigo-500', 'text-indigo-600');
            activeButton.classList.remove('border-transparent', 'text-slate-500');
        }

        // 如果是地图标签页，重新初始化地图
        if (tabName === 'map' && this.data.regional_analysis) {
            const { jd, wd } = this.data.regional_analysis;
            if (jd && wd) {
                setTimeout(() => {
                    this.initRegionalMap(jd, wd);
                }, 100);
            }
        }
    }

    exportDetail() {
        try {
            // 创建导出数据（使用修复后的字段名）
            const exportData = {
                basic_info: {
                    petition_record_id: this.data.petition_record_id,
                    tsr: this.data.tsr,
                    ts_xzq: this.data.ts_xzq,
                    dzxx_ds: this.data.dzxx_ds,
                    dzxx_xzq: this.data.dzxx_xzq,
                    dzxx_jd: this.data.dzxx_jd,
                    bfdw: this.data.bfdw,
                    djsj: this.data.djsj,
                    created_at: this.data.created_at,
                    tsms: this.data.tsms,
                    tszy: this.data.tszy,
                    hfnr: this.data.hfnr,
                    bz: this.data.bz
                },
                regional_analysis: this.data.regional_analysis,
                complaint_type_analysis: this.data.complaint_type_analysis,
                sentiment_analysis: this.data.sentiment_analysis,
                compliance_analysis: this.data.compliance_analysis,
                duplicate_analysis: this.data.duplicate_analysis,
                export_time: new Date().toISOString()
            };

            // 创建并下载JSON文件
            const dataStr = JSON.stringify(exportData, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `petition_ledger_detail_${this.recordId}.json`;
            link.click();
            URL.revokeObjectURL(url);

            NotificationService.success('导出成功');
        } catch (error) {
            console.error('导出失败:', error);
            NotificationService.error('导出失败');
        }
    }

    async loadDetail() {
        try {
            showLoading();

            const response = await fetch(`/api/petition-ledger/${this.recordId}`);

            if (response.ok) {
                const result = await response.json();
                console.log('API返回数据:', result); // 调试日志
                if (result.code === 200) {
                    this.data = result.data;
                    console.log('详情数据:', this.data); // 调试日志
                    this.renderDetail();
                } else {
                    throw new Error(result.message || '加载详情失败');
                }
            } else if (response.status === 404) {
                throw new Error('信访记录不存在');
            } else if (response.status === 403) {
                throw new Error('没有权限访问此记录');
            } else {
                throw new Error(`网络请求失败: ${response.status}`);
            }
        } catch (error) {
            console.error('加载详情失败:', error);
            NotificationService.error(error.message || '加载详情失败');

            // 显示错误信息
            this.showErrorState(error.message);
            throw error;
        } finally {
            hideLoading();
        }
    }

    showErrorState(message) {
        const mainContent = document.querySelector('.space-y-6');
        if (mainContent) {
            mainContent.innerHTML = `
                <div class="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
                    <i class="fas fa-exclamation-triangle text-red-400 text-4xl mb-4"></i>
                    <h3 class="text-lg font-semibold text-red-800 mb-2">加载失败</h3>
                    <p class="text-red-600 mb-4">${message}</p>
                    <button onclick="window.location.href='/web/petition-ledger'"
                            class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
                        <i class="fas fa-arrow-left mr-2"></i>返回列表
                    </button>
                </div>
            `;
        }
    }

    renderDetail() {
        console.log('开始渲染详情数据，原始数据:', this.data); // 调试日志

        // 渲染基础信息
        this.renderBasicInfo(this.data.basic_info || this.data);

        // 渲染投诉内容
        this.renderComplaintContent(this.data.basic_info || this.data);

        // 渲染分析结果
        this.renderRegionalAnalysis(this.data.regional_analysis);
        this.renderComplaintTypeAnalysis(this.data.complaint_type_analysis);
        this.renderSentimentAnalysis(this.data.sentiment_analysis);
        this.renderComplianceAnalysis(this.data.compliance_analysis);
        this.renderDuplicateAnalysis(this.data.duplicate_analysis);

        // 初始化标签页切换
        this.initTabSwitching();

        console.log('详情数据渲染完成'); // 调试日志
    }

    renderBasicInfo(info) {
        console.log('渲染基础信息，数据:', info); // 调试日志

        // 安全地更新基础信息，避免null元素引用错误
        const elements = {
            petitionId: document.getElementById('petitionId'),
            petitioner: document.getElementById('petitioner'),
            region: document.getElementById('region'),
            city: document.getElementById('city'),
            district: document.getElementById('district'),
            street: document.getElementById('street'),
            targetUnit: document.getElementById('targetUnit'),
            createdAt: document.getElementById('createdAt'),
            registrationTime: document.getElementById('registrationTime'),
            fullAddress: document.getElementById('fullAddress')
        };

        // 安全设置基础信息 - 根据后端返回的字段名进行调整
        this.safeSetText(elements.petitionId, info.petition_record_id || '-');
        this.safeSetText(elements.petitioner, info.petitioner_name || info.tsr || '-');
        this.safeSetText(elements.region, info.region || info.ts_xzq || '-');
        this.safeSetText(elements.city, info.city || info.province || info.dzxx_ds || '-');
        this.safeSetText(elements.district, info.district || info.dzxx_xzq || '-');
        this.safeSetText(elements.street, info.district || info.dzxx_jd || '-');
        this.safeSetText(elements.targetUnit, info.respondent_unit || info.ts_qxdw || '-');
        this.safeSetText(elements.createdAt, this.formatDateTime(info.created_at));
        this.safeSetText(elements.registrationTime, this.formatDateTime(info.created_at)); // 使用created_at替代djsj

        // 设置完整地址
        const fullAddress = [
            info.province || info.dzxx_ds,
            info.city || info.dzxx_xzq,
            info.district || info.dzxx_jd,
            info.region || info.ts_xzq
        ].filter(addr => addr && addr.trim()).join(' ');
        this.safeSetText(elements.fullAddress, fullAddress || '-');

        console.log('基础信息渲染完成'); // 调试日志
    }

    renderRegionalAnalysis(data) {
        // 安全地更新区域分析数据，避免null元素引用错误
        const elements = {
            longitude: document.getElementById('longitude'),
            latitude: document.getElementById('latitude'),
            analysisRegion: document.getElementById('analysisRegion'),
            analysisCity: document.getElementById('analysisCity'),
            analysisDistrict: document.getElementById('analysisDistrict'),
            analysisStreet: document.getElementById('analysisStreet'),
            analysisAddress: document.getElementById('analysisAddress'),
            fullAddress: document.getElementById('fullAddress'),
            coordinateInfo: document.getElementById('coordinateInfo')
        };

        if (!data) {
            // 安全地设置默认值
            this.safeSetText(elements.longitude, '-');
            this.safeSetText(elements.latitude, '-');
            this.safeSetText(elements.analysisRegion, '-');
            this.safeSetText(elements.analysisCity, '-');
            this.safeSetText(elements.analysisDistrict, '-');
            this.safeSetText(elements.analysisStreet, '-');
            this.safeSetText(elements.analysisAddress, '-');
            this.safeSetText(elements.fullAddress, '-');
            this.safeSetText(elements.coordinateInfo, '-');
            return;
        }

        // 修复字段名映射并安全设置值 - 根据后端返回的字段名进行调整
        this.safeSetText(elements.longitude, data.longitude || data.dzxx_lng || '-');
        this.safeSetText(elements.latitude, data.latitude || data.dzxx_lat || '-');
        this.safeSetText(elements.analysisRegion, data.region || data.ts_xzq || '-');
        this.safeSetText(elements.analysisCity, data.city || data.province || data.dzxx_ds || '-');
        this.safeSetText(elements.analysisDistrict, data.district || data.dzxx_xzq || '-');
        this.safeSetText(elements.analysisStreet, data.district || data.dzxx_jd || '-');
        this.safeSetText(elements.analysisAddress, data.region || data.ts_xzq || '-');

        // 设置完整地址
        const fullAddress = [
            data.province || data.dzxx_ds,
            data.city || data.dzxx_xzq,
            data.district || data.dzxx_jd,
            data.region || data.ts_xzq
        ].filter(addr => addr && addr.trim()).join(' ');
        this.safeSetText(elements.fullAddress, fullAddress || '-');

        // 设置坐标信息
        const longitude = data.longitude || data.dzxx_lng;
        const latitude = data.latitude || data.dzxx_lat;
        if (longitude && latitude) {
            this.safeSetText(elements.coordinateInfo, `经度: ${longitude}, 纬度: ${latitude}`);
            // 初始化地图
            this.initRegionalMap(longitude, latitude);
        } else {
            this.safeSetText(elements.coordinateInfo, '-');
        }
    }

    initRegionalMap(longitude, latitude) {
        // 检查Leaflet是否已加载
        if (typeof L === 'undefined') {
            console.warn('Leaflet未加载，无法显示地图');
            return;
        }

        const mapContainer = document.getElementById('map'); // 修复地图容器ID
        if (!mapContainer) {
            console.warn('地图容器不存在');
            return;
        }

        if (mapContainer) {
            mapContainer.innerHTML = ''; // 清空容器
        } else {
            console.warn('地图容器不存在');
            return;
        }

        try {
            // 初始化地图
            const map = L.map(mapContainer).setView([latitude, longitude], 13);

            // 添加地图瓦片
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors',
                maxZoom: 19
            }).addTo(map);

            // 添加标记
            L.marker([latitude, longitude]).addTo(map)
                .bindPopup('信访地点')
                .openPopup();

            // 添加圆形标记
            L.circle([latitude, longitude], {
                color: 'blue',
                fillColor: '#30f',
                fillOpacity: 0.2,
                radius: 500
            }).addTo(map);

            // 更新坐标信息
            const coordinateInfo = document.getElementById('coordinateInfo');
            if (coordinateInfo) {
                coordinateInfo.textContent = `经度: ${longitude}, 纬度: ${latitude}`;
            }

        } catch (error) {
            console.error('初始化地图失败:', error);
            if (mapContainer) {
                mapContainer.innerHTML = `
                    <div class="text-center text-gray-500">
                        <i class="fas fa-exclamation-triangle text-2xl mb-2"></i>
                        <p>地图加载失败</p>
                    </div>
                `;
            }
        }
    }

    renderComplaintTypeAnalysis(data) {
        // 安全地更新投诉类型分析数据
        const elements = {
            primaryType: document.getElementById('primaryType'),
            secondaryType: document.getElementById('secondaryType'),
            tertiaryType: document.getElementById('tertiaryType'),
            typeDescription: document.getElementById('typeDescription'),
            typeKeywords: document.getElementById('typeKeywords')
        };

        if (!data) {
            this.safeSetText(elements.primaryType, '-');
            this.safeSetText(elements.secondaryType, '-');
            this.safeSetText(elements.tertiaryType, '-');
            this.safeSetText(elements.typeDescription, '-');
            if (elements.typeKeywords) {
                elements.typeKeywords.innerHTML = '<p class="text-gray-500">暂无关键词</p>';
            }
            return;
        }

        // 修复字段名映射并安全设置值 - 根据后端返回的字段名进行调整
        this.safeSetText(elements.primaryType, data.primary_type || data.tslx_yj || '-');
        this.safeSetText(elements.secondaryType, data.secondary_type || data.tslx_rj || '-');
        this.safeSetText(elements.tertiaryType, data.tertiary_type || data.tslx_sj || '-');
        this.safeSetText(elements.typeDescription, '分类说明信息'); // 添加分类说明

        // 渲染分类关键词 - 后端暂未返回关键词数据
        if (elements.typeKeywords) {
            elements.typeKeywords.innerHTML = '<p class="text-gray-500">暂无关键词</p>';
        }

        // 初始化投诉类型图表
        this.initComplaintTypeChart(data);
    }

    initComplaintTypeChart(data) {
        // 检查Chart.js是否已加载
        if (typeof Chart === 'undefined') {
            console.warn('Chart.js未加载，无法显示图表');
            return;
        }

        const chartContainer = document.getElementById('complaintTypeChart');
        if (!chartContainer) {
            console.warn('图表容器不存在，无法显示投诉类型图表');
            return;
        }
        chartContainer.innerHTML = '<canvas id="complaintTypeCanvas" width="400" height="200"></canvas>';

        const canvas = document.getElementById('complaintTypeCanvas');
        if (!canvas) {
            console.warn('图表画布不存在，无法显示投诉类型图表');
            return;
        }
        const ctx = canvas.getContext('2d');

        // 准备图表数据
        const labels = [];
        const dataValues = [];
        const colors = ['#3B82F6', '#10B981', '#F59E0B'];

        if (data.primary_type) {
            labels.push('一级分类');
            dataValues.push((data.primary_confidence || data.confidence || 0) * 100);
        }
        if (data.secondary_type) {
            labels.push('二级分类');
            dataValues.push((data.secondary_confidence || data.confidence || 0) * 100);
        }
        if (data.tertiary_type) {
            labels.push('三级分类');
            dataValues.push((data.tertiary_confidence || data.confidence || 0) * 100);
        }

        if (labels.length === 0) {
            if (chartContainer) {
                chartContainer.innerHTML = `
                    <div class="text-center text-gray-500 py-8">
                        <i class="fas fa-chart-pie text-2xl mb-2"></i>
                        <p>暂无投诉类型分析数据</p>
                    </div>
                `;
            }
            return;
        }

        try {
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: dataValues,
                        backgroundColor: colors.slice(0, labels.length),
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.label + ': ' + context.parsed.toFixed(1) + '%';
                                }
                            }
                        }
                    }
                }
            });
        } catch (error) {
            console.error('初始化投诉类型图表失败:', error);
            if (chartContainer) {
                chartContainer.innerHTML = `
                    <div class="text-center text-gray-500">
                        <i class="fas fa-exclamation-triangle text-2xl mb-2"></i>
                        <p>图表加载失败</p>
                    </div>
                `;
            }
        }
    }

    renderSentimentAnalysis(data) {
        // 安全地更新情感分析数据
        const elements = {
            sentimentType: document.getElementById('sentimentType'),
            sentimentStatus: document.getElementById('sentimentStatus'),
            sentimentSummary: document.getElementById('sentimentSummary'),
            sentimentKeywords: document.getElementById('sentimentKeywords')
        };

        if (!data) {
            this.safeSetText(elements.sentimentType, '-');
            this.safeSetText(elements.sentimentStatus, '-');
            this.safeSetText(elements.sentimentSummary, '-');
            if (elements.sentimentKeywords) {
                elements.sentimentKeywords.innerHTML = '<p class="text-gray-500">暂无关键词</p>';
            }
            return;
        }

        // 修复字段名映射并安全设置值 - 根据后端返回的字段名进行调整
        this.safeSetText(elements.sentimentType, this.getSentimentTypeText(data.sentiment_type || data.qgfx_lx));
        this.safeSetText(elements.sentimentStatus, '正常'); // 添加情感状态
        this.safeSetText(elements.sentimentSummary, data.summary || data.qgfx_zy || '-');

        // 渲染关键词
        if (data.keywords && data.keywords.length > 0) {
            this.renderKeywords(data.keywords);
        } else {
            const keywordsContainer = document.getElementById('sentimentKeywords');
            if (keywordsContainer) {
                keywordsContainer.innerHTML = '<p class="text-gray-500">暂无关键词</p>';
            }
        }
    }

    renderKeywords(keywords) {
        const keywordsContainer = document.getElementById('sentimentKeywords');

        if (!keywordsContainer) {
            return;
        }

        if (!keywords || keywords.length === 0) {
            keywordsContainer.innerHTML = '<p class="text-gray-500">暂无关键词</p>';
            return;
        }

        try {
            const keywordArray = typeof keywords === 'string' ? JSON.parse(keywords) : keywords;

            keywordsContainer.innerHTML = keywordArray.map(keyword => `
                <span class="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">
                    ${keyword}
                </span>
            `).join('');
        } catch (error) {
            console.error('解析关键词失败:', error);
            keywordsContainer.innerHTML = '<p class="text-gray-500">关键词解析失败</p>';
        }
    }

    renderComplianceAnalysis(data) {
        // 安全地更新规范性分析数据
        const elements = {
            complianceStatus: document.getElementById('complianceStatus'),
            complianceScore: document.getElementById('complianceScore'),
            complianceSummary: document.getElementById('complianceSummary'),
            complianceRecommendations: document.getElementById('complianceRecommendations')
        };

        if (!data) {
            this.safeSetText(elements.complianceStatus, '-');
            this.safeSetText(elements.complianceScore, '-');
            this.safeSetText(elements.complianceSummary, '-');
            this.safeSetText(elements.complianceRecommendations, '-');
            return;
        }

        // 修复字段名映射 - 根据后端返回的字段名进行调整
        const isCompliant = data.is_compliant || (data.gffx_zt === '1');
        const statusText = isCompliant ? '合规' : '不合规';
        const statusClass = isCompliant
            ? 'text-lg font-semibold text-green-600'
            : 'text-lg font-semibold text-red-600';

        this.safeSetText(elements.complianceStatus, statusText);
        if (elements.complianceStatus) {
            elements.complianceStatus.className = statusClass;
        }

        this.safeSetText(elements.complianceScore, isCompliant ? '100/100' : '0/100');
        this.safeSetText(elements.complianceSummary, data.reason || data.gffx_pdly || '-');
        this.safeSetText(elements.complianceRecommendations, data.suggestions || '无建议');
    }

    renderComplaintContent(data) {
        // 安全地更新投诉内容 - 这些字段在基础信息中，需要从后端模型中获取
        const elements = {
            complaintContent: document.getElementById('complaintContent'),
            complaintSummary: document.getElementById('complaintSummary'),
            responseContent: document.getElementById('responseContent'),
            remarks: document.getElementById('remarks')
        };

        // 注意：这些字段在后端PetitionRecord模型中，但当前API未返回
        // 这里使用模拟数据或默认值
        this.safeSetText(elements.complaintContent, '投诉内容暂未获取');
        this.safeSetText(elements.complaintSummary, '概况信息暂未获取');
        this.safeSetText(elements.responseContent, '答复内容暂未获取');
        this.safeSetText(elements.remarks, '备注信息暂未获取');
    }

    renderDuplicateAnalysis(data) {
        // 安全地更新重复分析数据
        const elements = {
            duplicateStatus: document.getElementById('duplicateStatus'),
            duplicateCount: document.getElementById('duplicateCount'),
            duplicateSummary: document.getElementById('duplicateSummary'),
            similarRecords: document.getElementById('similarRecords')
        };

        if (!data) {
            this.safeSetText(elements.duplicateStatus, '-');
            this.safeSetText(elements.duplicateCount, '-');
            this.safeSetText(elements.duplicateSummary, '-');
            if (elements.similarRecords) {
                elements.similarRecords.innerHTML = '<p class="text-gray-500">暂无相似记录</p>';
            }
            return;
        }

        // 修复字段名映射 - 根据后端返回的字段名进行调整
        const isDuplicate = data.is_duplicate || (data.cfbh !== null && data.cfbh !== '');
        const statusText = isDuplicate ? '是' : '否';
        const statusClass = isDuplicate
            ? 'text-lg font-semibold text-red-600'
            : 'text-lg font-semibold text-green-600';

        this.safeSetText(elements.duplicateStatus, statusText);
        if (elements.duplicateStatus) {
            elements.duplicateStatus.className = statusClass;
        }

        this.safeSetText(elements.duplicateCount, isDuplicate ? '1' : '0');
        this.safeSetText(elements.duplicateSummary, data.duplicate_reason || data.cfzy || '-');

        // 显示相似记录 - 后端暂未返回相似记录数据
        if (elements.similarRecords) {
            elements.similarRecords.innerHTML = '<p class="text-gray-500">暂无相似记录</p>';
        }
    }

    renderRelatedRecords(records) {
        const container = document.getElementById('relatedRecords');

        if (!container) {
            console.warn('相关记录容器不存在');
            return;
        }

        if (!records || records.length === 0) {
            container.innerHTML = `
                <div class="text-center text-gray-500 py-4">
                    <i class="fas fa-inbox text-2xl mb-2"></i>
                    <p>暂无相关记录</p>
                </div>
            `;
            return;
        }

        container.innerHTML = records.map(record => `
            <div class="border border-gray-200 rounded-lg p-3 hover:bg-gray-50 transition-colors cursor-pointer" onclick="viewRelatedRecord(${record.id})">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-900">分析任务 #${record.analysis_task_id}</p>
                        <p class="text-xs text-gray-500">${record.region || '未知区域'}</p>
                    </div>
                    <div class="text-right">
                        <p class="text-xs text-gray-500">${this.formatDate(record.created_at)}</p>
                        <span class="inline-block px-1 py-0.5 text-xs rounded ${this.getStatusClass(record.analysis_status)}">
                            ${this.getStatusText(record.analysis_status)}
                        </span>
                    </div>
                </div>
            </div>
        `).join('');
    }

  
    initCharts() {
        // 重新初始化图表（如果数据存在）
        if (this.data) {
            if (this.data.complaint_type_analysis) {
                this.initComplaintTypeChart(this.data.complaint_type_analysis);
            }
            if (this.data.regional_analysis) {
                const { longitude, latitude } = this.data.regional_analysis;
                if (longitude && latitude) {
                    this.initRegionalMap(longitude, latitude);
                }
            }
        }
    }

    getStatusClass(status) {
        const statusMap = {
            'completed': 'bg-green-100 text-green-800',
            'processing': 'bg-yellow-100 text-yellow-800',
            'pending': 'bg-gray-100 text-gray-800'
        };
        return statusMap[status] || 'bg-gray-100 text-gray-800';
    }

    getStatusText(status) {
        const statusMap = {
            'completed': '已完成',
            'processing': '处理中',
            'pending': '待处理'
        };
        return statusMap[status] || status || '未知';
    }

    getSentimentTypeText(sentimentType) {
        const sentimentMap = {
            'positive': '正面',
            'neutral': '中性',
            'negative': '负面'
        };
        return sentimentMap[sentimentType] || sentimentType || '未知';
    }

    // 安全设置文本内容的方法
    safeSetText(element, text) {
        if (element) {
            element.textContent = text;
        }
    }

    formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    formatDateTime(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }
}

// 全局函数
function viewRelatedRecord(recordId) {
    window.location.href = `/web/petition-ledger/${recordId}`;
}

// 页面加载完成后自动初始化
document.addEventListener('DOMContentLoaded', function() {
    // 从URL中获取recordId参数
    const pathParts = window.location.pathname.split('/');
    const recordId = pathParts[pathParts.length - 1];

    if (recordId && !isNaN(recordId)) {
        // 创建详情页面实例
        if (!window.petitionLedgerDetail) {
            window.petitionLedgerDetail = new PetitionLedgerDetail(parseInt(recordId));
        }
    } else {
        console.error('无法从URL中获取有效的记录ID');
        NotificationService.error('无效的记录ID');
    }
});